﻿using System;
using System.Windows;
using System.Windows.Threading;
using BrainTechLLC;
using BrainTechLLC.Communications;
using BrainTechLLC.WebCam;

namespace WebCamViewer
{
    /// <summary>
    /// Interaction logic for WebCamWindow.xaml
    /// </summary>
    public partial class WebCamWindow : Window
    {
        public WebcamVideoControl WebCam;
        public P2PCommunicationsLibrary commAudio = new P2PCommunicationsLibrary();
        public P2PCommunicationsLibrary commVideo = new P2PCommunicationsLibrary();

        public WebCamWindow()
        {
            InitializeComponent();
            this.Closing += new System.ComponentModel.CancelEventHandler(WebCamWindow_Closing);
        }

        void WebCamWindow_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            if (WebCam != null)
            {
                WebCam.StopProcessingImages();
                WebCam.StopRunning();
                commAudio.GracefulShutdown();
                commVideo.GracefulShutdown();
            }
        }

        private void Window_KeyDown(object sender, System.Windows.Input.KeyEventArgs e)
        {
            if (e.Key == System.Windows.Input.Key.Escape)
            {
                e.Handled = true;
                this.Close();
            }
        }

        private void webCamControl_Load(object sender, EventArgs e)
        {
            commAudio.AcceptIncomingConnections(System.Net.IPAddress.Any, 4005);
            commVideo.AcceptIncomingConnections(System.Net.IPAddress.Any, 4006);
            WebCam = webCamControl;
            var results = WebcamVideoControl.GetAvailableCaptureDevices(null);
            // HEREHERE
            WebCam.OpenCaptureDevice(results[0]);

            WebCam.comm = commVideo;
            WebCam.EnableRemoteConnections = true;
            Dispatcher.BeginInvoke(new VoidDelegate(() => WebCam.BeginProcessingImages(this.formsHost, true, true)));
            DispatcherTimer tmr = new DispatcherTimer()
            {
                IsEnabled = true,
                Interval = new TimeSpan(0, 0, 0, 1)
            };
            tmr.Tick += new EventHandler(tmr_Tick);
            tmr.Start();
            webCamControl.MotionDetected += new MotionDetectedEvent(webCamControl_MotionDetected);
            //btnConnect_Click(null, new RoutedEventArgs());
        }

        void webCamControl_MotionDetected(object o, MotionDetectedEventArgs args)
        {
            Dispatcher.BeginInvoke(new VoidDelegate(() => txtMotion.Text = "Motion at " + DateTime.Now.ToShortTimeString()));
            
            if (_movementAlarmOn)
            {
                Dispatcher.BeginInvoke(new VoidDelegate(() =>
                {
                    this.Topmost = true;
                    btnTopmost.IsChecked = true;
                    this.Activate();
                    this.BringIntoView();
                    this.Focus();

                    System.Media.SystemSounds.Exclamation.Play();
                    btnMovementAlarm.IsChecked = false;
                }));

                _movementAlarmOn = false;
                
            }
        }

        void tmr_Tick(object sender, EventArgs e)
        {
            if (webCamControl.SelectedImageSource == WebcamVideoControl.VideoImageSource.RemoteServer &&
                webCamControl.LastReceivedFrame != DateTime.MinValue)
            {
                if (DateTime.Now > webCamControl.LastReceivedFrame.AddSeconds(2))
                {
                    txtWarning.Text = "X";
                }
                else
                {
                    txtWarning.Text = "";
                }
            }
            txtFPS.Text = webCamControl.FramesPerSecond.ToString("N2") + " FPS";
        }

        private void btnConnect_Click(object sender, RoutedEventArgs e)
        {
            WebCam.ConnectToComputer = txtAddress.Text;
            WebCam.ConnectToPort = 4006;
            WebCam.ConnectToRemoteHost = true;
            WebCam.SelectedImageSource = WebcamVideoControl.VideoImageSource.RemoteServer;
        }

        private void btnTopmost_Checked(object sender, RoutedEventArgs e)
        {
            this.Topmost = true;
            this.Activate();
        }

        private void btnTopmost_Unchecked(object sender, RoutedEventArgs e)
        {
            this.Topmost = false;
            this.Activate();
        }

        private void formsHost_SizeChanged(object sender, SizeChangedEventArgs e)
        {
            int wid = (int)this.ActualWidth;
            int hei = (int)this.ActualHeight;
            if (wid <= 0 || hei <= 0)
                return;

            webCamControl.DesiredHeightOnScreen = (int)this.ActualHeight;
            webCamControl.DesiredWidthOnScreen = (int)this.ActualWidth;
            if (webCamControl.Width != wid + 4 ||
                webCamControl.Height != hei)
            {
                webCamControl.Width = wid;
                webCamControl.Height = hei;
            }
        }

        private void webCamControl_SizeChanged(object sender, EventArgs e)
        {
            int wid = (int)this.ActualWidth;
            int hei = (int)this.ActualHeight;
            if (wid <= 0 || hei <= 0)
                return;

            webCamControl.DesiredHeightOnScreen = (int)this.ActualHeight;
            webCamControl.DesiredWidthOnScreen = (int)this.ActualWidth;
            if (webCamControl.Width != wid + 4 ||
                webCamControl.Height != hei)
            {
                webCamControl.Width = wid;
                webCamControl.Height = hei;
            }
        }

        private void txtMotion_MouseLeftButtonDown(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
            txtMotion.Text = string.Empty;
        }

        public bool _movementAlarmOn;
        private void btnMovementAlarm_Checked(object sender, RoutedEventArgs e)
        {
            _movementAlarmOn = true;
        }

        private void btnMovementAlarm_Unchecked(object sender, RoutedEventArgs e)
        {
            _movementAlarmOn = false;
        }
    }
}
